import React, { Component } from 'react';
import { history } from 'umi';
class Index extends Component {
  params = (list:any) => {
    //参数动态拼接
    let result = '';
    let item;
    for (item in list) {
      if (list[item] && String(list[item])) {
        result += `&${item}=${list[item]}`;
      }
    }
    if (result) {
      result = '?' + result.slice(1);
    }
    return result;
  };
  componentDidMount(){
    const iframe = document.getElementsByTagName('iframe')[0];
    let win;
    // some browser (don't remember which one) throw exception when you try to access
    // contentWindow for the first time, it work when you do that second time
    try {
        win = iframe.contentWindow;
    } catch(e) {
        win = iframe.contentWindow;
    }
    const obj = {
       token: localStorage.getItem('token'),
      //  idUrlMaps: JSON.parse(localStorage.getItem("programInfo")).idUrlMaps,
       domain:window.location.origin,
    };
    
    iframe.addEventListener('load',function(){
      win.postMessage(JSON.stringify({data: obj}), "*");
    })
    
    window.addEventListener("message", function( event ) {
      // 接收编辑页面发过来的数据并进行页面跳转到计划发布
      if(event && event.data){
        const data = event.data;
        if(typeof data =='string' && data.constructor==String){
          if(data.indexOf("playConfig") >-1){//一键发布
            const state = JSON.parse(data).data?.state;
            if(state){
              localStorage.setItem("planUpdate",'true');
              history.push({pathname:'/plan/list/new',state:state});
            }
          }else if(data.indexOf("refreshToken")>-1){//刷新token
            const token = JSON.parse(data).data?.refreshToken;
            localStorage.setItem("token",token);
          }else if(data.indexOf('planUpdate')>-1){//节目保存和退出
            const planUpdate = JSON.parse(data).data?.state.planUpdate;
            localStorage.setItem("planUpdate",planUpdate);

          }
          
        }
        
      }
    }, false); 
  }

  render() {
    const storage = JSON.parse(localStorage.programInfo);
    const programInfo = new Object();
    for(let key in storage){
      if(key != "idUrlMaps"){
        programInfo[key] = storage[key];
        // programInfo['android'] = true;
      }
    }
    // let src = 'http://'+window.location.hostname+`:8081/${this.params(programInfo)}&random=${Math.random()}`;
    console.log(window.location);
    let src = window.location.protocol + '//' + window.location.hostname+`:8081/${this.params(programInfo)}&random=${Math.random()}`;
    return (
      <iframe
        title=""
        id="edit_iframe"
        src={src}
        style={{ width: '100%', border: '0px', height: '100%', position: 'absolute' }}
        sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-top-navigation"
        scrolling="auto"
      />
    );
  }
}
export default Index;
